#include "SpWorker.h"
#include <QDebug>

SpWorker::SpWorker(QObject *parent)
    : QObject(parent),
      rxBuffer_()
{

}

SpWorker::~SpWorker()
{
    if (sp_) {
        sp_->close();
        delete sp_;
        sp_ = nullptr;
    }
}

bool SpWorker::isSpConnected()
{
    return isSpConnected_;
}

void SpWorker::onNotifyConnectSP(const QString &s)
{
    if (sp_ == nullptr)
        sp_ = new QSerialPort;

    if (!sp_->isOpen()) {
        sp_->setPortName(s);
        sp_->setBaudRate(115200);
        sp_->setParity(QSerialPort::Parity::NoParity);
        sp_->setStopBits(QSerialPort::StopBits::OneStop);
        connect(sp_, &QSerialPort::readyRead, this, &SpWorker::onSpDataReadyRead);
        if (!sp_->open(QIODevice::ReadWrite)) {
            emit SpError(tr("Can't open %1, error code %2")
                       .arg(s).arg(sp_->error()));
            return;
        }

        isSpConnected_ = true;
    }
}

void SpWorker::onNotifySend()
{
    if (txBuffer_.size() > 0) {
        sp_->write(txBuffer_);
        txBuffer_.clear();
    }
}

/// 没必要
//void SpWorker::onNotifyExit()
//{
//    if (sp_) {
//        sp_->close();
//        delete sp_;
//        sp_ = nullptr;
//    }
//}

void SpWorker::onSpDataReadyRead()
{
    rxBuffer_ += sp_->readAll();
    while (sp_->waitForReadyRead(10))
        rxBuffer_ += sp_->readAll();

    while (rxBuffer_.size() > 4) {

    }
}

void SpWorker::setTxBuffer(const QByteArray &txBuffer)
{
    txBuffer_ = txBuffer;
}
